import datetime
import requests
import json
import xlwt



dealers = []

headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Cookie': 'AMCV_B52D1CFE5330949C0A490D45%40AdobeOrg=1406116232%7CMCIDTS%7C17624%7CMCMID%7C75920106889297974241924037998203827132%7CMCAAMLH-1523243842%7C11%7CMCAAMB-1523243842%7C6G1ynYcLPuiQxYZrsz_pkqfLG9yMXBpb2zX5dvJdYQJzPXImdj0y%7CMCOPTOUT-1522646242s%7CNONE%7CMCAID%7CNONE%7CvVersion%7C2.5.0; __clickidc=152040767815912050; s_lv=1522640267452; a=2Icje0SoM399; bw=5000Kbps+; bmwdtm_hq_cc=true; check=true; mbox=session#d933028552f14985831952495fbf36dd#1522642126; AMCVS_B52D1CFE5330949C0A490D45%40AdobeOrg=1; bmwdtm_hq_sid=i3233PoiIaTT; bmwdtm_hq_pcg=fastlane%7Cfastlane%20%3E%20dealer-locator%7Cfastlane%20%3E%20dealer-locator%7Cfastlane%20%3E%20dealer-locator%7Cdealer-locator; s_lv_s=More%20than%207%20days; s_cc=true; bmwdtm_hq_vs=1522639045',
    'Host': 'cn-digital2-app.bmw.com.cn',
    'Pragma': 'no-cache',
    'Referer': 'http://www.bmw.com.cn/zh/fastlane/dealer-locator.html',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0',
}
# 获得城市和省份的response
getProCity = "https://cn-digital2-app.bmw.com.cn/dlo/init"
pro_city_res = requests.get(getProCity,headers=headers);
# 根据返回的response取出json字符串格式的值
pro_city_text = pro_city_res.text
start_pro = pro_city_text.index("{")
pro_city_dict = json.loads(pro_city_text[start_pro:-1])
# 解析json字符串,得到省份list,城市list,服务类型list
response_body = pro_city_dict["responseBody"]
pro_list = response_body["provinces"]
city_list = response_body["cities"]
service_type_list = response_body["servicetypes"]
# 重构省份的list,放入一个新的pro_dict
pro_dict = {}
for pro_id_name in pro_list:
    pro_id = pro_id_name["id"]
    pro_name = pro_id_name["nz"]
    pro_dict[pro_id] = pro_name

# 重构服务类型的list,放入一个新的type_dict
type_dict = {}
for type_id_name in service_type_list:
    type_id = type_id_name["code"]
    type_name = type_id_name["nz"]
    type_dict[type_id] = type_name
# 获得经销商

# 遍历城市
for city in city_list:
    pro_id = city["pv"]
    city_id = city["id"]
    city_name = city["nz"]
    get_dealer = "https://cn-digital2-app.bmw.com.cn/dlo/outlet?province=" +pro_id + "&city=" + city_id
    res_dealers = requests.get(get_dealer, headers=headers)
    start_dealer = res_dealers.text.index("{")
    dealers_dict = json.loads(res_dealers.text[start_dealer:-1])
    dealers_list = dealers_dict["responseBody"]["outlets"]
    for dealer in dealers_list:
        dealer_name = dealer["nz"]
        dealer_address = dealer["az"]
        dealer_sell = dealer["tel"]

        dealer_type = ""
        if 1 == dealer["rtlFmt"]["display"]:
            dealer_type = dealer["rtlFmt"]["textZh"]
        service_codes = dealer["serviceCodes"]

        two_hand = ""
        if "20" in service_codes:
            two_hand = "√"

        big = ""
        if "03" in service_codes:
            big = "√"

        bmwi = ""
        if "05" in service_codes:
            bmwi = "√"

        bmwm = ""
        if "06" in service_codes:
            bmwm = "√"

        dealer_info = {"name": dealer_name,
                       "sell_tell": dealer_sell,
                       "address": dealer_address,
                       "type": dealer_type,
                       "big": big,
                       "two_hand": two_hand,
                       "bmwi": bmwi,
                       "bmwm": bmwm,
                       }
        dealers.append(dealer_info)

# 直接写入Excel表格中
book = xlwt.Workbook(encoding="utf-8")
sheet = book.add_sheet("test", cell_overwrite_ok=True)
today = str(datetime.date.today())


sheet.write(0, 0, "经销商名称")
sheet.write(0, 1, "电话")
sheet.write(0, 2, "地址")
sheet.write(0, 3, "网点类型")
sheet.write(0, 4, "大客户")
sheet.write(0, 5, "二手车认证")
sheet.write(0, 6, "BMW i标示")
sheet.write(0, 7, "BMW m标示")

for index in range(len(dealers)):
    param = dealers[index]
    sheet.write(index + 1, 0, param["name"])
    sheet.write(index + 1, 1, param["sell_tell"])
    sheet.write(index + 1, 2, param["address"])
    sheet.write(index + 1, 3, param["type"])
    sheet.write(index + 1, 4, param["big"])
    sheet.write(index + 1, 5, param["two_hand"])
    sheet.write(index + 1, 6, param["bmwi"])
    sheet.write(index + 1, 7, param["bmwm"])

    print(index + 1)
    book.save(r'./宝马'+today+'.xls')

